<?php
namespace App\Libs\Common;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 *   支付宝资金授权冻结
 */
class AlFundController extends Controller
{	

		private $aop=null;
		
		private $freeze_notify_url="https://n.lvyuecp.com/OutApi/AlFund/notify";//服务器异步通知页面路径
		private $freeze_return_url="https://n.lvyuecp.com/OutApi/AlFund/return_url";//页面跳转同步通知页面路径
		private $return_url_url="https://n.lvyuecp.com/waphb/success.html?describe=";//下单成功或失败跳转页面路径
		
		//ceshi
		// private $freeze_notify_url="http://47.93.56.255:88/lvyue/OutApi/AlFund/notify";//测试服务器异步通知页面路径
		// private $freeze_return_url="http://47.93.56.255:88/lvyue/OutApi/AlFund/return_url";//测试页面跳转同步通知页面路径
		// private $return_url_url="http://192.168.31.198:8080/success.html?describe=";//测试下单成功或失败跳转页面路径

		private $alipay_config=[
								"partner"=>'2088721798968241',
								"key"=>'hneycz9cpwbcsg7krtzksfazydv8vbo5',
								"sign_type"=>'MD5',
								"input_charset"=>'utf-8',
								//"cacert"=>getcwd().'/cacert.pem', // ca证书路径地址，用于curl中ssl校验
								"cacert"=>'/cacert.pem',
								"transport"=>'http', // 访问模式,根据自己的服务器是否支持ssl访问，若支持请选择https；若不支持请选择http
								];
									
		public function _initialize()
		{   
			header("Content-type: text/html; charset=utf-8");
			vendor("ali_pay_auth.lib.alipay_submit");

		}



		public function test()
		{
			$out_request_no='201807130001100111';
			$out_order_no='201807130001100111233';
			$this->freeze($out_request_no,$out_order_no,"0.01","圣罗兰女神妍活青春粉底液#B20 30ml");
		}


		/**
		 * 授权冻结
		 * 
		 * @param   out_request_no [商户请求流水号]
		 * @param   out_order_no   [商户授权资金订单号]
		 * @param   amount         [冻结金额]
		 * @param   goods_name     [商品名称]
		 */
		public function freeze($out_request_no,$out_order_no,$amount,$goods_name)
		{
	        //服务器异步通知页面路径
	        //$notify_url = "http:n.lvyuecp.com/OutApi/AlFund/notify";
	        $notify_url = $this->freeze_notify_url;

	        //需http://格式的完整路径，不能加?id=123这类自定义参数

	        //页面跳转同步通知页面路径
	        $return_url = $this->freeze_return_url;
	        //需http://格式的完整路径，不能加?id=123这类自定义参数，不能写成http://localhost/

	        //订单标题
	        $order_title = $goods_name;

			//构造要请求的参数数组，无需改动
			$parameter = array(
					"service" => "alipay.fund.auth.create.freeze.apply",
					"partner" => trim($this->alipay_config['partner']),
					"notify_url"	=> $notify_url,
					"return_url"	=> $return_url,
					"out_order_no"	=> $out_order_no,
					"out_request_no"	=> $out_request_no,
					"product_code"	=> "FUND_PRE_AUTH",          //业务产品码   
					"scene_code"	=> "ELECTRONIC_COMMERCE",   //对应业务场景，商户签约时由支付宝统一分配。
					"order_title"	=> $order_title,
					"amount"	=> $amount,
			        "pay_mode"      => "WIRELESS", //支付模式 电脑：PC  无线：WIRELESS
			        "payee_logon_id"      =>"guoshengnan@lvyuechupin.com",
			        "payee_user_id"      => "2088721798968241",
					"_input_charset"	=>$this->alipay_config['input_charset']
			);

			//建立请求
			$alipaySubmit = new \AlipaySubmit($this->alipay_config);
			$html_text = $alipaySubmit->buildRequestForm($parameter,"get", "确认");

			echo $html_text;
		}
		

		/**
		 * 
		 * @return [type] [description]
		 */
		public function return_url()
        {
        	$request=I();

        	//先存入记录表
        	$request["creat_time"]=date("Y-m-d H:i:s",time());
        	M("hb_dj")->add($request);

        	//接口调用成功,并不表明业务处理结果
        	$is_success=$request['is_success'];
        	//操作流水状态
        	$status=$request['status'];

        	//支付宝资金授权单号
        	$data['auth_no']=$request['auth_no'];
        	//商户授权资金订单号
        	$data['out_order_no']=$request['out_order_no'];
        	//支付宝资金操作流水号
        	$data['operation_id']=$request['operation_id'];
        	//商户请求流水号
        	$data['out_request_no']=$request['out_request_no'];
        	//冻结金额
        	$dat['amount']=$request['amount'];

        	//成功
            if ('SUCCESS' == $status)
            {
             	M("orders")->where("order_id='$data[out_order_no]'")->save(array("order_status"=>2));
             	$describe='SUCCESS';
            }

            // 处理中
            if ('PROCESSING' == $status) 
            {
             	$describe='PROCESSING';
            }

            // 失败
            if ('FAIL' == $status) 
            {	
            	$goods_id=M("orders")->where("order_id='$data[out_order_no]'")->getField("goods_id");
             	$describe='FAIL';
            }

            if (!empty($goods_id))
            {	
            	$url=$this->return_url_url.$describe."&goods_id=".$goods_id;
            }else{
            	$url=$this->return_url_url.$describe;	
            }
            
            Header("Location:$url");
        }


        /**
         * 授权异步通知
         * @return [type] [description]
         */
        public function notify()
        {	
        	$request=I("");

        	$status=$request['status'];
        	$out_order_no=$request['out_order_no'];

        	$data["yb_order_status"]=$request['order_status'];
        	$data["yb_payer_user_id"]=$request['payer_user_id'];
        	$data["yb_payer_logon_id"]=$request['payer_logon_id'];
        	$data["yb_json"]=json_encode($request);
        	$data["yb_notify_time"]=$request['notify_time'];

        	$yb_order_status=M("hb_dj")->where("out_order_no='$out_order_no'")->getField("yb_order_status");

        	if (empty($yb_order_status)) 
        	{
        		M("hb_dj")->where("out_order_no='$out_order_no'")->save($data);
        	}

        	if ($status == 'SUCCESS') 
        	{
        		$order_status=M("orders")->where("order_id='$out_order_no'")->getField("order_status");
        		if($order_status == 0)
        		{	
	             	$row=M("orders")->where("order_id='$out_order_no'")->field("goods_id,user_phone")->find();
	             	//商品浏览量统计
	        		goods_statia($row["goods_id"],$row["user_phone"],2); 

        			M("orders")->where("order_id='$out_order_no'")->save(array("order_status"=>2));
        		}else{
        			echo "success";
        		}
        	}
        }



		/**
		 *  预授权解冻(部分和全部)
		 *  @param  auth_no        支付宝资金授权订单号
		 *  @param  out_order_no   商户流水号
		 *  @param  amount         金额
		 */
		public function unfreeze($auth_no,$out_order_no,$amount)
		{
			$parameter = array(

						"service" => "alipay.fund.auth.unfreeze",
						"partner" => trim($this->alipay_config['partner']),
						"notify_url" => "https://n.lvyuecp.com/OutApi/AlFund/unfreeze_notify",
						"_input_charset"	=> trim(strtolower($this->alipay_config['input_charset'])),
						"auth_no"	=>$auth_no,
						"out_request_no"	=> $out_order_no,
						"amount"	=> $amount,
						"remark"	=>"绿悦出品解冻"
				);	

			//建立请求
			$alipaySubmit = new \AlipaySubmit($this->alipay_config);
			
			$html_text = $alipaySubmit->buildRequestHttp($parameter);

			$xmlarray=xmlToArray($html_text);

			$result=$xmlarray['response']['order'];
		
			if ("SUCCESS" == $result['result_code']) 
			{
				return true;
			}else{
				return false;
			}
		}

		//解冻异步通知
		public function unfreeze_notify()
		{
			echo "success"; 
		}

		/**
		 * 资金授权取消
		 * @return [type] [description]
		 */
		public function cancel()
		{
               
		}


        /**
         *  预授权查询
         *  @param  auth_no          支付宝授权资金订单号
		 *  @param  out_order_no     商户的授权资金订单号-与支付宝授权资金订单号不能同时为空
		 *  @param  operation_id     支付宝的授权资金操作流水号
		 *  @param  out_request_no   商户的授权资金操作流水号
         */
        public function query($auth_no,$out_order_no,$operation_id,$out_request_no)
        {
        	
        }


        


        /**
         * 使用预授权资金完成支付
         *
         * @param [out_trade_no] [商户网站唯一订单号]
         * @param [total_fee]    [金额]
         * @param [buyer_id]     [买家ID]
         * @param [auth_no]      [支付宝授权号]
         * 
         */
        public function pay($out_trade_no,$total_fee,$buyer_id,$auth_no)
        {
        	//异步通知地址
        	//$notify_url="http://47.93.56.255:88/lvyue/OutApi/AlFund/pay_notify";
        	$notify_url="https://n.lvyuecp.com/OutApi/AlFund/pay_notify";

        	//卖家ID
        	$seller_id=trim($this->alipay_config['partner']);

			$parameter = array(
						"service" => "alipay.acquire.createandpay",
						"partner" => trim($this->alipay_config['partner']),
						"_input_charset"	=> trim(strtolower($this->alipay_config['input_charset'])),
						"notify_url"	=>$notify_url,
						"out_trade_no"	=>$out_trade_no,
						"subject"	=>"绿悦出品",
						"product_code"	=>"FUND_TRADE_FAST_PAY",
						"total_fee"	=>$total_fee,
						"seller_id"	=>$seller_id,
						"buyer_id"	=>$buyer_id,
						"auth_no"	=>$auth_no
				);	

			//建立请求
			$alipaySubmit = new \AlipaySubmit($this->alipay_config);
			
			$html_text = $alipaySubmit->buildRequestHttp($parameter);

			$xmlarray=xmlToArray($html_text);
			
			$result=$xmlarray['response']['alipay'];
			
			return $result;
        }

        /**
         * 支付异步地址
         * @return [type] [description]
         */
        public function pay_notify()
        {	
        	$request=I("");

        	$trade_status=$request['trade_status'];
        	$out_trade_no=$request['out_trade_no'];
        	$total_fee=$request['total_fee'];
        	//$price=$request['price'];
            $trade_no = $request['trade_no'];//支付宝交易号
        	if ($trade_status == 'TRADE_SUCCESS') 
        	{
        		$row=M('pay_dk_bill')->where("out_trade_no='$out_trade_no'")->field("dk_status,stages_id")->find();

        		save_order_stages($row["stages_id"],$total_fee,$trade_no);

	            if ($row["dk_status"] == 0 || $row["dk_status"] == 1)
	            {
	                M('pay_dk_bill')->where("out_trade_no='$out_trade_no' and dk_status in(0,1)")->save(array('dk_status'=>2,'last_time'=>$time,'keyword'=>$res['msg']));
	            }else{
	            	echo "success";
	            }
	            
        	}

        	file_put_contents('Uploads/log/pay_notify_'.time()."_AlFund_异步通知.txt",json_encode($request));
        }
        
		


	
}